package com.usian.article.config;

import io.seata.core.context.RootContext;
import io.seata.tm.api.GlobalTransaction;
import io.seata.tm.api.GlobalTransactionContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.hbase.thirdparty.io.netty.handler.traffic.GlobalTrafficShapingHandler;
import org.apache.ibatis.transaction.TransactionException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
@Slf4j
public class WorkAspect {

    @Before("execution(* com.usian.article.controller.*.*(..))")
    public void before(JoinPoint joinPoint) throws TransactionException, io.seata.core.exception.TransactionException {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        GlobalTransaction tx = GlobalTransactionContext.getCurrentOrCreate();
        tx.begin(300000,"tran");
    }
    @AfterThrowing(throwing = "e",pointcut = "execution(* com.usian.article.controller.*.*(..))")
    public void doRecoveryActions(Throwable e) throws TransactionException, io.seata.core.exception.TransactionException {
        if (!StringUtils.isBlank(RootContext.getXID())){
            GlobalTransactionContext.reload(RootContext.getXID()).rollback();
        }
    }
}
